<template>
  <div class="components-container"
       v-loading=loading
       element-loading-text="拼命加载中"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-form ref="form" :model="form" :rules="rules" label-width="50px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="概述" prop="overview">
        <el-input v-model="form.overview" placeholder="请输入概述"></el-input>
      </el-form-item>

      <el-form-item label="标签" prop="labelId">
        <el-select v-model="form.labelId" placeholder="请选择标签">
          <el-option v-for="item in allLabel" :label="item.title" :value="item.id" ></el-option>
        </el-select>
        <span style="margin-left: 80px;margin-right: 10px">小标签</span>
        <el-button @click="addDomain">新增</el-button>
        <el-button @click="removeDomain(form.tag[form.tag.length-1])">删除</el-button>
        <el-tooltip class="item" effect="dark" content="当前修改的博客Id" placement="right">
          <el-tag style="margin-left: 80px" size="medium" effect="dark" type="warning">{{blogId==null?'未指定':blogId}}</el-tag>
        </el-tooltip>
      </el-form-item>

      <!--      <el-form-item label="小标签" prop="tag">-->
      <!--        <el-input v-model="form.tag" placeholder="多个小标签以','分隔"></el-input>-->
      <!--      </el-form-item>-->
      <el-row>
        <el-col :span="4"
                v-for="(item, index) in form.tag"
                :key="index">
          <el-form-item>
            <el-input v-model="form.tag[index]" :placeholder="'必填'+(index+1)"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="主图">
        <el-row>
          <el-col :span="3">
            <el-upload
              :show-file-list=false
              class="upload-demo"
              :on-change="fileOnChange"
              action="http://localhost"
              :before-upload="beforeUp"
            >
              <el-button size="small" type="primary">{{uploadBut}}</el-button>
            </el-upload>
          </el-col>
          <el-col :span="3">
          <span v-if="imageUrl.length!==0">
            <el-popover
              placement="right"
              width="330"
              trigger="click">
              <el-button  slot="reference" size="small" type="success">查看主图</el-button>
              <img :src="imageUrl" alt="" width="300px" height="180">
            </el-popover>
          </span>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>



    <div>
      <tinymce v-model="content" :height="450" @saveDraft="saveDraft" @submit="submit"/>
    </div>

    <div class="editor-content" v-html="content" />
  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import {getToken} from '@/api/qiniu'
  import * as qiniu from "qiniu-js";
  import {getLabel,updateBlog,getBlogById} from '@/api/blog'

  export default {
    name: 'updateBlog',
    components: { Tinymce },
    data() {
      return {
        blogId: null,
        loading: false,
        uploadBut:'点击上传',
        imageUrl:'',
        content:
          `<h3 style="text-align: center;">写博客要善于挖坑</h3>`,
        allLabel:[],
        form:{
          title:'',
          overview:'',
          labelId:'',
          tag:[],
          image: ''
        },
        rules:{
          title:[
            { required: true, message: '请输入标题', trigger: 'blur' },
          ],
          overview:[
            { required: true, message: '请输入概述', trigger: 'blur' },
          ],
          labelId:[
            { required: true, message: '请选择标签', trigger: 'change' }
          ],
          tag:[
            { required: true, message: '请输入小标签', trigger: 'blur' }
          ]
        }
      }
    },
    created(){
      const blogId=this.$route.params.blogId;
      if((this.blogId==null&&blogId!=null)||this.blogId!=null){
        this.blogId=blogId;
        this.loading=true;
        getBlogById(blogId).then(res=>{
          const data=res.data;
          console.log(data)
          this.form.title=data.title;
          this.form.overview=data.overview;
          this.form.labelId=data.labelId;
          this.form.tag=data.tag.split(",");
          this.imageUrl=data.image;
          this.form.image=data.image;
          this.form.content=data.content;
          this.content=data.content;
          console.log(this.form);
          this.loading=false;
        })
      }else{
        const h = this.$createElement;
        this.$notify({
          title: '警告',
          message: h('i', { style: 'color: teal'}, '未选择目标博客'),
          type: 'warning',
          duration: 2000
        });
      }

      if(this.allLabel.length===0)
        getLabel().then(res=>{
          console.log(res)
          this.allLabel=res.data;
        })
    },
    methods:{
      saveDraft(){
        console.log('存为草稿')
        const data=this.examine();
        if(!data){
          return;
        }
        data.status=0;
        data.id=this.blogId;
        this.loading=true
        updateBlog(data).then(res=>{
          console.log(res)
          this.loading=false
          this.$router.replace({name:'blogManagement',params:{
              op:"1"
            }})
        })
      },
      submit(){
        console.log('发布')
        const data=this.examine();
        if(!data){
          return;
        }
        data.status=1;
        data.id=this.blogId;
        this.loading=true
        updateBlog(data).then(res=>{
          console.log(res)
          this.loading=false
          this.$router.replace({name:'blogManagement',params:{
              op:"1"
            }})
        })
      },
      examine(){
        const data={
          title:this.form.title,
          overview:this.form.overview,
          labelId:this.form.labelId,
          tag:this.form.tag,
          image:this.form.image,
          content:this.content
        }
        console.log(data)
        if(data.title.length===0){
          this.$message.error('请填写标题');
          return false;
        }
        if(data.overview.length===0){
          this.$message.error('请填写概述');
          return false;
        }
        if(data.labelId.length===0){
          this.$message.error('请填写标签');
          return false;
        }
        if(data.tag.length===0){
          this.$message.error('请填写小标签');
          return false;
        }else{
          const tags=data.tag;
          for(let i=0;i<tags.length;i++){
            tags[i]=tags[i].trim();
            console.log(tags[i])
            if(tags[i].length===0||tags[i]===''){
              this.$message.error('请填写有效小标签');
              return false;
            }
          }
        }
        if(data.image.length===0){
          this.$message.error('请上传图片');
          return false;
        }
        if(data.content.length===0){
          this.$message.error('请填写内容');
          return false;
        }
        if(this.blogId==null){
          this.$message.error('未选择目标博客');
          return false;
        }
        return data;
      },
      removeDomain(item) {
        if(this.form.tag.length===1) {
          this.$message('至少一条标签');
          return;
        }
        const index = this.form.tag.indexOf(item)
        if (index !== -1) {
          this.form.tag.splice(index, 1)
        }
      },
      addDomain() {
        if(this.form.tag.length===6) {
          this.$message('最多六条标签');
          return;
        }
        this.form.tag.push('');
      },
      beforeUp(file){//都是false
        const isLt5M = file.size / 1024 / 1024 < 5;
        if(!isLt5M){
          this.$message.error('上传图片大小不能超过 5MB!');
        }

        if(file.type.indexOf('image')!==-1) {
          getToken().then(response => {
            console.log(response)
            const token = response.data.qiniu_token;
            const key = response.data.qiniu_key;
            const url = response.data.qiniu_url;
            const config = {useCdnDomain: true};
            //file文件 ket文件名 token凭证 putExtra上传时的附加信息 config一些配置
            const observable = qiniu.upload(file, key, token, {}, config)
            let _this=this;
            const observer = {
              next(res) {
              },
              error(err) {
              },
              complete(res) {
                _this.uploadBut='点击修改';
                _this.imageUrl=url;
                _this.form.image=url;
                _this.$message.success('上传成功!');
                _this.loading=false
              }
            }
            observable.subscribe(observer) // 上传开始
          }).catch(err => {
            this.$message.error('出现未知问题');
            console.log(err);
          });
        }
        else {
          this.$message.error('只能上传图像!');
        }
        return false;//借力,用七牛云sdk上传
      },
      fileOnChange(){
        this.loading=true
      },
    },
    watch:{
      $route(to,from){
        if(to.name!=="updateBlog"){
          return;
        }
        console.log("我是修改页面")
        const blogId=this.$route.params.blogId;
        if((this.blogId==null&&blogId!=null)||this.blogId!=null){
          if(this.blogId!=null&&blogId===this.blogId){//已经加载过了+重复加载
            return;
          }
          if(blogId===undefined)
            return;

          this.blogId=blogId;
          this.loading=true;
          getBlogById(blogId).then(res=>{
            const data=res.data;
            console.log(data)
            this.form.title=data.title;
            this.form.overview=data.overview;
            this.form.labelId=data.labelId;
            this.form.tag=data.tag.split(",");
            this.imageUrl=data.image;
            this.form.image=data.image;
            this.form.content=data.content;
            this.content=data.content;
            console.log(this.form)
            this.loading=false;
          })
        }else{
          const h = this.$createElement;
          this.$notify({
            title: '警告',
            message: h('i', { style: 'color: teal'}, '未选择目标博客'),
            type: 'warning',
            duration: 2000
          });
        }
      }
    }
  }
</script>

<style scoped>
  .editor-content{
    margin-top: 20px;
  }
</style>
